package com.dzsw.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.lang.reflect.Type;

/**
 * @author by wdw
 * @description gosn工具类
 * @date 2019/9/24 10:33
 */
public class GsonUtils {
    private static Gson gson = new Gson();

    /**
     * 对象转成json
     *
     * @param object 对象
     * @return json字符串
     */
    public static String objectToJson(Object object) {
        String jsonStr = null;
        if (gson != null) {
            jsonStr = gson.toJson(object);
        }
        return jsonStr;
    }

    /**
     * 对象转成json 不过滤空对象
     *
     * @param object 对象
     * @return json字符串
     */
    public static String objectToJsonWithNull(Object object) {
        GsonBuilder gsonbuilder = new GsonBuilder();
        gsonbuilder.serializeNulls();
        Gson gsonWithNull = gsonbuilder.create();
        return gsonWithNull.toJson(object);
    }


    /**
     * json转成bean
     *
     * @param jsonStr json字符串
     * @param cls 反向类
     * @return Bean对象
     */
    public static <T> T jsonToBean(String jsonStr, Class<T> cls) {
        T t = null;
        if (gson != null) {
            t = gson.fromJson(jsonStr, cls);
        }
        return t;
    }

    /**
     * 将json转化为对应的实体对象
     * new TypeToken<HashMap<String, Object>>(){}.getType()
     */
    public static <T>  T fromJson(String json, Type type){
        return gson.fromJson(json, type);
    }
}